package cn.kwq.pcsystem.utils;

import cn.hutool.captcha.CaptchaUtil;
import cn.hutool.captcha.ShearCaptcha;
import cn.hutool.core.util.IdUtil;
import cn.hutool.core.util.StrUtil;


import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.*;

/**
 * Created with IntelliJ IDEA.
 *
 * @Author: kwq
 * @Date: 2023/01/05/20:10
 * @Description: 验证码工具类
 */
public class CaptchaUtils {

    /**
     * 生成验证码并且返回到前端
     *
     * @param response http返回对象
     * @return 返回uuid
     * @throws IOException
     */
    public static String generateCaptcha(HttpServletResponse response) throws IOException {
        try {
            //定义图形验证码的长、宽、验证码字符数、干扰线宽度
            ShearCaptcha captcha = CaptchaUtil.createShearCaptcha(200, 100, 4, 4);
            //设置类型
            response.setContentType("image/jpeg");
            //浏览器不缓存
            response.setHeader("Pragma", "No-cache");
            //写入响应
            captcha.write(response.getOutputStream());
            //生成唯一的uuid
            String UUID = IdUtil.simpleUUID();
            // DONE: 2023/1/5 存入redis，UUID作为KEY
            String code = captcha.getCode();//验证码
            RedisUtils.setStr("Captcha-"+UUID,code,60*30L);
            return UUID;
        }finally {
            // 关闭流
            response.getOutputStream().close();

        }
    }

    /**
     * 生成验证码并且返回base64
     * @return 返回uuid和base64的图片
     * @throws IOException
     */
    public static Map<String,String> generateCaptcha() throws IOException {

            //定义图形验证码的长、宽、验证码字符数、干扰线宽度
            ShearCaptcha captcha = CaptchaUtil.createShearCaptcha(200, 100, 4, 4);
            //生成唯一的uuid
            String UUID = IdUtil.simpleUUID();
            // DONE: 2023/1/5 存入redis，UUID作为KEY
            String code = captcha.getCode();//验证码
            RedisUtils.setStr("Captcha-"+UUID,code,60*30L);
            //返回base64
            Map<String,String> map=new HashMap<>();
            map.put("base64Data",captcha.getImageBase64Data());
            map.put("base64Img",captcha.getImageBase64());
            map.put("UUID",UUID);
            return map;

    }

    /**
     * 验证验证码正确与否
     * @param captcha 验证码
     * @param UUID 图片的uuid
     * @return 验证结果
     */
    public static boolean checkCaptcha(String captcha,String UUID){
        if (UUID==null){
            throw new RuntimeException("UUID错误");
        }
        // DONE: 2023/1/5 redis取出验证码
        String key = RedisUtils.getStr("Captcha-" + UUID);
        return StrUtil.equals(key,captcha);

    }

}
